/**
 * 开单页中显示商品信息模块
 * 主要逻辑为，如果第一个商品选择的是本科室的商品，后续的商品只能限制选择本科室的（商品名前带了👑图标的为本科室商品）
 * 如果第一个商品选择的是其他科室的商品，后续的商品只能选择非本科室的商品
 */
import React, { useState, useRef, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Divider, Button, Tooltip, Form, message, Row, Col } from 'antd';
import { EditableProTable } from '@ant-design/pro-table';
import { RedoOutlined, PlusOutlined } from '@ant-design/icons';
import { OptType } from '@/utils/constants';
import { useModel } from 'umi';
import type { FormInstance } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import {
  getZcSpecsList
} from '@/services/stock-goods/api';
import GoodName from '@/components/Select/GoodName';
import { isNull, showMsg, isSupportSticky } from '@/utils/utils';
import styles from '../onceOrder/style.less';
import { getSubGoodsSpecsList } from '@/services/stock-goods/subApi';

interface ItemInfoProps {
  type?: string,
  updateGoodsList: (goodsList: any) => void;
  list?: STOCKGOODSAPI.GoodsItem[];
  yuanlist?: STOCKGOODSAPI.GoodsItem[];
}

const ItemInfo: React.FC<ItemInfoProps> = forwardRef((props, ref) => {
  const {
    type,
    updateGoodsList,
    list,
    yuanlist,
  } = props;

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [editForm] = Form.useForm();
  const { initialState } = useModel('@@initialState');

  // 数据
  const [dataSource, setDataSource] = useState<any[]>(list || []);

  // 新增数量
  const [newAddNums, setNewAddNums] = useState<number>(0);

  // 更新数
  const [updateNums, setUpdateNums] = useState<number>(0);

  // 删除数
  const [deleteNums, setDeleteNums] = useState<number>(0);

  // 选中的第一个商品科室code
  const [filterVal, setFilterVal] = useState('');

  // 当前选中的行编号，用于定位颜色
  const [clickRow, setClickRow] = useState('');


  // 获得当前rowKey的dataSource数据
  const getRowByKey = (rowKey) => {
    return dataSource.filter(item => item.id === rowKey);
  }

  const ggChange = (specItem, form, rowKey, fromData) => {
    const goodsItem: STOCKGOODSAPI.GoodsItem = form.getFieldsValue()[rowKey as string];
    // console.log('goodsItem', goodsItem)
    goodsItem.goods_num = 1;
    goodsItem.specs_name = specItem.specs_name;
    form.setFieldsValue({ [rowKey || '']: goodsItem });


    const result = fromData.findIndex(item => item.id === rowKey);
    if (result > -1) {
      console.log('specItemspecItem', specItem)
      fromData[result].price = specItem?.price;
      fromData[result].goods_num = 1;
      fromData[result].goods_total_price = Number(specItem?.price as number) * 1;
      fromData[result].specs_name = specItem.specs_name;
      // console.log('dataSourceaaa', dataSource)
      setDataSource(Object.assign([], fromData));
      updateGoodsList(Object.assign([], fromData));
    }
  }

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    isNull: () => dataSource.length === 0,
    validate: () => {
      return editForm.validateFields().then(values => {
        const result = dataSource.filter(item => !item.disabled);
        return isNull(result) || !result;
      }).catch(errorInfo => {
        return false;
      });
    },
    clear: () => {
      setNewAddNums(0);
      setUpdateNums(0);
      setDeleteNums(0);
      setDataSource([]);
      setEditableRowKeys([]);
      editForm.resetFields();
      actionRef.current?.reload();
    },
    addLine: () => {
      const id = `new_${Date.now()}`;
      setDataSource([{
        id, specsList: [], disabled: false,
      }]);
      setEditableRowKeys([id]);
    },
  }))

  const columns: ProColumns<STOCKGOODSAPI.GoodsItem>[] = [
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      valueType: 'select',
      width: 250,
      // editable: (val, record) => record.disabled,
      fieldProps: (val, { entity }) => {
        return {
          disabled: entity.disabled,
        }
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项'
          }
        ]
      },
      renderFormItem: (form1, record1, form, e) => {
        // console.log('form1, record1', form1, form, e)
        const record = form1.entity;
        // console.log('record1', record1, record)
        // value={`${record.goods_id}|${record.goods_py}|${record.brand_name}|${record.goods_name}`}
        return (
          <GoodName fromTo='zc' disabled={record.disabled} noStyle allowClear={false}
            name1={`goods_name_${record1.recordKey}_${form1.index}`} value1={record.goods_id}
            filterVal={form1.index === 0 ? '' : filterVal}
            onChange={e => {
              console.log('选中的商品', e);
              const obj = {
                class_name: e.class_name,
                goods_id: e.goods_id,
                goods_name: e.goods_name,
                brand_id: e.brand_id,
                brand_name: e.brand_name,
                obj: e,
                id: record1.recordKey,
                goods_dept_code: e.create_dept_code,
                specs_name: null,
                price: null,
                goods_num: null,
                goods_total_price: null,
                discount: null,
                discount_price: null,
              }
              const result = dataSource.findIndex(item => item.id === record1.recordKey);

              if (result > -1) {
                form.setFieldsValue({ [record1.recordKey]: obj })
                if (form1.index === 0) {
                  if (!isNull(filterVal) && e.create_dept_code !== filterVal) {
                    setDataSource(Object.assign([], [obj]));
                    fetchGoodsSpecsList(e.goods_id, e.create_dept_code, 0, [obj], form, record1.recordKey);
                    setFilterVal(e.create_dept_code);
                    return;
                  }
                  setFilterVal(e.create_dept_code);
                }
                dataSource[result] = obj;
                setDataSource(Object.assign([], dataSource));
                fetchGoodsSpecsList(e.goods_id, e.create_dept_code, result, dataSource, form, record1.recordKey);
              }
            }}
          />
        )
      },
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      editable: false,
      width: 110,
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name',
      valueType: 'select',
      width: 180,
      fieldProps: (form, record) => {
        // console.log('规格', record, dataSource);
        return {
          disabled: record.entry.disabled,
          dropdownMatchSelectWidth: false,
          optionLabelProp: "text",
          size: 'small',
          options: ((dataSource[record.rowIndex] || {}).specsList || []).map(item => {
            return {
              className: styles.specSelectOption,
              label: item.specs_name,
              value: item.specs_name as string,
            }
          }),
          showSearch: false,
          allowClear: false,
          onChange: (value: any) => {
            const specItem = (dataSource[record.rowIndex].specsList || []).find(item => item.specs_name === value);
            ggChange(specItem, form, record.rowKey, dataSource);
          }
        }
      },
      formItemProps: {
        rules: [
          {
            // required: true,
            message: '此项是必填项'
          }
        ]
      }
    },
    {
      title: '单价',
      dataIndex: 'price',
      editable: false,
      valueType: 'money',
      align: 'right',
    },
    {
      title: '数量',
      dataIndex: 'goods_num',
      valueType: 'digit',
      width: 60,
      align: 'right',
      // editable: (val, record) => isNull(record.disabled) || !record.disabled,
      fieldProps: (form, { rowKey, rowIndex, entity }) => {
        return {
          disabled: entity.disabled,
          precision: 0,
          style: {
            width: '100%'
          },
          // min: 1,
          max: 999,
          onChange: (value: number) => {
            if (isNull(value) || value < 1) {
              return;
            }
            const goodsItem = getRowByKey(rowKey)[0];
            if (goodsItem.price) {
              const price = parseFloat(Number(goodsItem.price) * value).toFixed(2);
              goodsItem.goods_total_price = price;
              dataSource[rowIndex].goods_total_price = price;
            }
            goodsItem.goods_num = value;
            dataSource[rowIndex].goods_num = value;
            form.setFieldsValue({ [rowKey || '']: goodsItem });
            setDataSource(Object.assign([], dataSource));
            updateGoodsList(Object.assign([], dataSource));
          }
        }
      },
      formItemProps: (myForm, record) => {
        const entry = record.entry;
        return {
          rules: [
            {
              required: true,
              message: '此项是必填项'
            },
            {
              validator: (e, val) => {
                if (val < 1) {
                  return Promise.reject(new Error(`数量最少为1!`));
                }
                if (val > 999) {
                  return Promise.reject(new Error(`数量最多为999!`));
                }
                return Promise.resolve();
              },
              message: `数量最少为 1，最多为 999`
            },
          ]
        }
      }
    },
    {
      title: '价格',
      dataIndex: 'goods_total_price',
      editable: false,
      valueType: 'money',
      align: 'right',
    },
    {
      title: '操作',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      width: 120,
      valueType: 'option',
    }
  ];

  // 复原
  const onRestore = () => {
    setNewAddNums(0);
    setUpdateNums(0);
    setDeleteNums(0);
    setDataSource(Object.assign([], yuanlist));
    // setDataSource(JSON.parse(JSON.stringify(yuanlist)));
    setTimeout(() => {
      editForm.resetFields();
      updateGoodsList(yuanlist);
    }, 100);
  }
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  // 商品规格
  const fetchGoodsSpecsList = async (goods_id: string, goods_dept_code: string, index: number, ary: Array, form, rowKey) => {
    try {
      const data = await getZcSpecsList(goods_id);
      ary[index].specsList = data || [];
      if (data.length === 1) {
        const cur = data[0];
        ggChange(cur, form, rowKey, ary);
      }
      setDataSource(Object.assign([], ary));
    } catch (error) {
      console.log('error', error)
      showMsg(error?.data?.errmsg);
    }
  }

  useEffect(() => {
    if (list.length > 0) {
      setFilterVal(list[0].goods_dept_code);
    }
    // const result = list.map(item => {return { ...item, disabled: true }})
    setDataSource(Object.assign([], list));
    setEditableRowKeys(list?.map(item => item.id));
  }, [list]);

  // 保存当前行商品信息，并禁用
  const saveCurLine = (row, disabled) => {
    console.log('row', row);
    if (!disabled) {
      editForm.validateFields().then(values => {
        dataSource[row].disabled = true;
        setDataSource(Object.assign([], dataSource));
      }).catch(errorInfo => {
        message.error('请先保存正在编辑的商品信息');
      });
    } else {
      const result = dataSource.filter(item => !item.disabled);
      if (isNull(result) || !result) {
        dataSource[row].disabled = false;
        setDataSource(Object.assign([], dataSource));
      } else {
        message.error('请先保存正在编辑的商品信息');
      }
    }
  }
  const addLine = () => {
    editForm.validateFields().then(values => {
      const result = dataSource.filter(item => !item.disabled);
      if (isNull(result) || !result) {
        const id = `new_${Date.now()}`;
        dataSource.push({ id, specsList: [], disabled: false }),
          setDataSource(Object.assign([], dataSource));
        editableKeys.push(id);
        setEditableRowKeys(Object.assign([], editableKeys));
      } else {
        message.error('请先保存正在编辑的商品信息');
      }
    }).catch(errorInfo => {
      message.error('请先保存正在编辑的商品信息');
    });
  }

  console.log('dataSourcedataSource', dataSource)


  // console.log('dataSource', dataSource)
  return <div className="service-record">
    <div className="header">
      <div className="title">2.商品信息</div>
    </div>
    <Divider style={{ margin: '10px 0 0' }} />
    <EditableProTable<any>
      rowKey="id"
      className='onceTable'
      formRef={formRef}
      actionRef={actionRef}
      style={{ marginTop: -8 }}
      rowClassName={(record) => {
        // console.log('rowClassName', record.id)
        if (record.id === clickRow) {
          return 'tableRowClick';
        }
        if (type === 'edit') {
          if ((record.id || '').includes('new')) {
            return 'new-add';
          }
          if (record.update) {
            return 'update-bg';
          }
        }
        return ''
      }}
      bordered
      value={dataSource}
      onChange={(e) => {
        setDataSource(e)
      }}
      onRow={record => {
        return {
          onClick: event => { setClickRow(record.id) }, // 点击行
          onMouseEnter: event => { }, // 鼠标移入行
          onMouseLeave: event => { },
        };
      }}
      toolbar={
        type === OptType.EDIT ? {
          menu: {
            type: 'inline',
            items: [
              {
                key: 'restore',
                label: <Button className='btnColor2' onClick={onRestore} type="primary" icon={<RedoOutlined />}>变更复原</Button>
              }
            ]
          }
        } : undefined}
      toolBarRender={() => [
        <div>
          {
            type === 'edit' &&
            <>
              <span>新增：</span>
              <span style={{ color: '#52C41A', fontWeight: 'bold' }}>{newAddNums}</span>
              <span style={{ paddingLeft: 20 }}>删除：</span>
              <span style={{ color: '#333', fontWeight: 'bold' }}>{deleteNums}</span>
              <span style={{ paddingLeft: 20 }}>变更：</span>
              <span style={{ color: '#FAAD15', fontWeight: 'bold' }}>{updateNums}</span>
            </>
          }
          <span style={{ paddingLeft: 20 }}>总数：</span>
          <span style={{ color: '#2E8DE6', fontWeight: 'bold' }}>{dataSource.length}</span>
        </div>
      ]}
      recordCreatorProps={
        {
          newRecordType: 'dataSource',
          record: () => ({
            id: `new_${Date.now()}`,
          }),
          style: {
            display: 'none',
          },
        }
      }
      recordCreatorProps={false}
      editable={{
        form: editForm,
        type: 'multiple',
        editableKeys,
        actionRender: (row, config, defaultDoms) => {
          // console.log('row', row);
          const disabled = (dataSource[row.index] || {}).disabled;
          return [
            <a onClick={() => saveCurLine(row.index, disabled)}>{disabled ? '编辑' : '保存'}</a>,
            defaultDoms.delete,
            disabled &&
            <a key="copy" onClick={() => {
              const id = `new_${Date.now()}`;
              dataSource.push({ ...row, id, disabled: false });
              setDataSource(Object.assign([], dataSource));
              editableKeys.push(id);
              setEditableRowKeys(editableKeys);
              updateGoodsList(Object.assign([], dataSource));
            }}>复制</a>]
        },
        onChange: setEditableRowKeys,
        onDelete: async (key, row) => {
          // console.log('ondelete', row)
          const list = dataSource.filter(item => item.id !== row.id);
          setDataSource(Object.assign([], list));
          if (!row.id.includes('new')) {
            setDeleteNums(deleteNums + 1);
          }
          updateGoodsList(Object.assign([], list));
        }
      }}
      columns={columns} />
    <Button onClick={() => addLine()} type="dashed" style={{ width: '100%', marginTop: 10 }} icon={<PlusOutlined />}>添加一行数据</Button>
  </div>
});
export default ItemInfo;
